﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using UnityEngine;

public class SimpleGifBundleCard : CardBase {

    //帧数(数值越大播放速度越快)
    public float Fps = 24;
    public List<Texture2D> _tex2DList = new List<Texture2D>();
    private float _time;
    private int _framCount;

    protected override void Start()
    {
        if (string.IsNullOrEmpty(imagePath)) return;

        AVProVideoPlayerMgr.Instance.Stop();

        if (imagePath.EndsWith(".gif"))
        {
            UnityEngine.Object o = PaperManager.Instance.GetAssetFromCurrentAssetBundle(imagePath);
            Debug.Log(o.GetType());
            //var image = Image.FromFile(imagePath);
            //_tex2DList = GifToTexture2D(image);
            //FixSize(new Vector2(_tex2DList[0].width, _tex2DList[0].height));
        }
    }

    protected override void FixedUpdate()
    {
        base.FixedUpdate();
    }

    /// <summary>
    /// Gif转Texture2D
    /// </summary>
    /// <param name="image"> System.Image</param>
    /// <returns>Texture2D集合</returns>
    private List<Texture2D> GifToTexture2D(Image image)
    {
        var tex = new List<Texture2D>();
        if (image == null) return tex;
        var frameDimension = new FrameDimension(image.FrameDimensionsList[0]);
        //获取指定维度的帧数
        _framCount = image.GetFrameCount(frameDimension);
        Debug.Log("gif总帧数 = " + _framCount);
 
        for (var i = 0; i < _framCount; i++)
        {
            image.SelectActiveFrame(frameDimension, i);
            var framBitmap = new Bitmap(image.Width, image.Height);
            using (var newGraphics = System.Drawing.Graphics.FromImage(framBitmap))
            {
                newGraphics.DrawImage(image, Point.Empty);
            }
            //这里涉及到gif显示逻辑的优化问题
            //经测试这里texture2d加载部分是造成卡顿的原因，考虑的解决方案是使用多线程，但可能面临一些问题
            //如果使用使用多线程的情况下这里考虑部分读取，在gif快播放完时开始加载下一部分（但必须多线程，否则肯定会卡顿）
            //所以这个问题暂不处理
            var frameTexture2D = new Texture2D(framBitmap.Width, framBitmap.Height, TextureFormat.ARGB32, true);
            frameTexture2D.LoadImage(BitmapToByte(framBitmap));
            frameTexture2D.filterMode = FilterMode.Trilinear;
            tex.Add(frameTexture2D);
        }
        return tex;
    }

    /// <summary>
    /// Bitmap转Byte
    /// </summary>
    /// <param name="bitmap">Bitmap</param>
    /// <returns>byte数组</returns>
    private byte[] BitmapToByte(Bitmap bitmap)
    {
        using (var stream = new MemoryStream())
        {
            bitmap.Save(stream, ImageFormat.Png);
            var data = new byte[stream.Length];
            stream.Seek(0, SeekOrigin.Begin);
            stream.Read(data, 0, Convert.ToInt32(stream.Length));
            return data;
        }
    }

    private void Update()
    {
        if (_tex2DList.Count <= 0) return;
        if (_framCount < 2) return;
        _time += Time.deltaTime;
        var index = (int)(_time * Fps) % _tex2DList.Count;
        Render.material.mainTexture = _tex2DList[index];
    }

    protected override void ReleaseResouces()
    {
        if (_tex2DList.Count > 0)
        {
            for (int i = 0; i < _tex2DList.Count; i++)
            {
                Destroy(_tex2DList[i]);
            }
            _tex2DList = null;
        }
    }
}
